package com.itheima.controller;

import com.itheima.global.BusinessException;
import com.itheima.po.R;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
//1、点击上传图片插入发送请求到服务器
//2、判断图片大小是否大于2M，如果大于2M则返回文件到前端
//3、如果不大于2M则继续获取图片文件名并重新命名，覆盖原有文件名避免文件名重复
//4、创建文件存放目录
//5、将图片上传到目录，指定文件名，同时响应到前端
//6、前端根据文件名下载图片
    private final static String dir = "E:\\BaiduNetdiskDownload\\heima-jichu\\reggie_take_out\\image";
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
        long size = file.getSize() / 1024 / 1024;
        if(size > 2){
            throw new BusinessException("上传图片不能超过2M");
        }
        String originalFilename = file.getOriginalFilename();
//        xxx.后缀
        String[] split = originalFilename.split("\\.");
        String suffix = split[split.length - 1];
        List<String> suffixList = Arrays.asList("PNG", "JPEG", "JPG","png", "jpeg", "jpg");
        if(!suffixList.contains(suffix)){
            throw new BusinessException("上传图片格式有误");
        }
//        md5 雪花算法 时间戳 随机数 UUID
        String newFileName = UUID.randomUUID().toString();
        File fileDir = new File(CommonController.dir);
        if(!fileDir.exists()){
            fileDir.mkdir();
        }
        try {
            file.transferTo(new File(dir+newFileName+"."+suffix));
        }catch (IOException e){
            System.out.println("file error");
            log.error("file error",e);
        }
        return R.success(newFileName+"."+suffix);
    }
    @GetMapping("/dowwnload")
    public void download(String name, HttpServletResponse httpServletResponse){
//        1、读取文件
//    2、通过httpresponse形成输出流，返回给前端
        try {
            FileInputStream fileInputStream = new FileInputStream(new File(dir + name));
            ServletOutputStream outputStream = httpServletResponse.getOutputStream();
            httpServletResponse.setContentType("image/jepg");
//                输入流复制给输出流
            byte[] bytes = new byte[1024];
//                为-1表明读取结束
            while (fileInputStream.read(bytes) != -1) {
                outputStream.write(bytes);
                outputStream.flush();
            }
            fileInputStream.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
